<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">安信借钱管理后台</h3>
      </div>
      <el-form-item prop="Saccount">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="account"
          v-model="loginForm.account"
          placeholder="账号"
          name="account"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-tooltip
        v-model="capsTooltip"
        content="Caps lock is On"
        placement="right"
        manual
      >
        <el-form-item prop="pwd">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="pwd"
            v-model="loginForm.pwd"
            :type="passwordType"
            placeholder="密码"
            name="pwd"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
      </el-tooltip>
      <el-form-item prop="phone">
        <div style="display:flex">
          <span class="svg-container">
            <svg-icon icon-class="edit" />
          </span>
          <el-input
            ref="phone"
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            name="phone"
            type="text"
            tabindex="3"
            autocomplete="on"
          >
          </el-input>
          <el-button type="primary" style="width:50%" v-show="show" @click="yz"
            >发送验证码</el-button
          >
          <el-button type="primary" style="width:50%" v-show="!show"
            >{{ count }}s后重新获取</el-button
          >
        </div>
      </el-form-item>

      <el-form-item prop="smsCode">
        <span class="svg-container">
          <svg-icon icon-class="form" />
        </span>
        <el-input
          ref="smsCode"
          v-model="loginForm.smsCode"
          placeholder="验证码"
          name="smsCode"
          type="text"
          tabindex="4"
          maxlength="6"
        />
      </el-form-item>

      <el-button
        :loading="loading"
        type="primary"
        style="width:100%;margin-bottom:30px;"
        @click.native.prevent="handleLogin"
        >登录</el-button
      >
      <!-- <div class="toqr" @click="goQRcode">
        <img src="@/assets/qrcode.png" alt="" />
      </div> -->
    </el-form>

    <el-dialog title="Or connect with" :visible.sync="showDialog">
      Can not be simulated on local, so please combine you own business
      simulation! ! !
      <br />
      <br />
      <br />
      <social-sign />
    </el-dialog>
  </div>
</template>
<script>
import { validUsername } from '@/utils/validate';
import { yanZheng } from '@/api/login';
import SocialSign from './components/SocialSignin';

export default {
  name: 'Login',
  components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('请输入正确的密码'));
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      if (value.length < 11) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };
    const validateSmsCode = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error('请输入验证码'));
      } else {
        callback();
      }
    };
    return {
      show: true,
      timer: null,
      count: '',
      loginForm: {
        account: '',
        pwd: '',
        phone: '',
        smsCode: ''
      },
      phone: '',
      loginRules: {
        account: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        pwd: [{ required: true, trigger: 'blur', validator: validatePassword }],
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        smsCode: [
          { required: true, trigger: 'blur', validator: validateSmsCode }
        ]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    }
  },
  created() {
    if (
      /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)
    ) {
      this.goQRcode();
    }
    window.addEventListener('storage', this.afterQRScan);
  },
  mounted() {
    if (this.loginForm.account === '') {
      this.$refs.account.focus();
    } else if (this.loginForm.pwd === '') {
      this.$refs.pwd.focus();
    }
  },
  methods: {
    goQRcode() {
      this.$router.replace({ path: 'qrlogin' });
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z');
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
      this.$nextTick(() => {
        this.$refs.pwd.focus();
      });
    },
    yz() {
      let phone = this.loginForm.phone;
      let data = {
        phone: phone
      };
      yanZheng(JSON.parse(JSON.stringify(data))).then(res => {
        this.show = false;
        const time = 60;
        if (!this.timer) {
          this.count = time;
          this.show = false;
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= time) {
              this.count--;
            } else {
              this.show = true;
              clearInterval(this.timer);
              this.timer = null;
            }
          }, 1000);
        }
        if (res.data.code === 200) {
          this.$notify({
            title: '验证码',
            message: '发送验证码成功！',
            type: 'success',
            duration: 2000
          });
        } else {
          this.$notify({
            title: '验证码',
            message: '发送验证码失败！',
            type: 'fail',
            duration: 2000
          });
        }
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          // console.log(this.loginForm);
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({
                path: this.redirect || '/',
                query: this.otherQuery
              });
              this.loading = false;
            })
            .catch(error => {
              this.$notify({
                title: '错误',
                message: error,
                type: 'fail',
                duration: 2000
              });
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    }
  }
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #4590eb;
$light_gray: black;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.toqr {
  margin-left: 423px;
  text-align: center;
  padding: 10px;
  position: absolute;
  margin-top: -343px;
}
.toqr img {
  height: 40px;
  width: 40px;
}
.toqr:hover {
  cursor: pointer;
}
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: #fff;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 60px 35px 30px;
    margin: 0 auto;
    overflow: hidden;
    border: 1px solid #1890ff;
    margin-top: 200px;
    border-radius: 5px;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: #1890ff;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}

.container {
  width: 302px;
  height: 400px;
  margin: 100px auto;
  padding-top: 10px;
  padding-right: 50px;
  padding-left: 50px;
  padding-bottom: 50px;
  background: #ffffff;
  border-radius: 3px;
}

.qrcode-title {
  text-align: left;
  font-size: 20px;
  margin-left: -20px;
}
.qrcode-content {
  text-align: center;
  margin-top: 40px;
  font-size: 20px;
}
</style>
